package cn.tedu.mintmall.service.Impl;

import cn.tedu.mintmall.dto.CategoryAddNewDTO;
import cn.tedu.mintmall.entity.Category;
import cn.tedu.mintmall.exception.MintmallServiceException;
import cn.tedu.mintmall.mapper.CategoryMapper;
import cn.tedu.mintmall.restful.ResponseCode;
import cn.tedu.mintmall.service.ICaegoryService;
import cn.tedu.mintmall.vo.CategoryDetailsVO;
import cn.tedu.mintmall.vo.CategorySimpleVO;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements ICaegoryService {
    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    public void addNew(CategoryAddNewDTO categoryAddNewDTO) {
        // 从参数中取出尝试添加的类别的名称
        String name = categoryAddNewDTO.getName();
        // 调用categoryMapper.getByName()方法查询
        CategorySimpleVO queryResult = categoryMapper.getByName(name);
        // 判断查询结果是否不为null
        if (queryResult != null) {
            // 是：抛出ServiceException
            throw new MintmallServiceException(ResponseCode.NOT_FOUND,"添加类别失败，名称（" + name + "）已存在！");
        }

        // 从参数中取出父级类别的id：parentId
        Long parentId = categoryAddNewDTO.getParentId();
        // 判断parentId是否为0，当前尝试新增的类别的depth默认为1
        Integer depth = 1;
        CategorySimpleVO parentCategory = null;
        if (parentId != 0) {
            // 否：此次尝试添加的不是一级类别，则应该存在父级类别，调用categoryMapper.getById()方法查询父级类别的信息
            parentCategory = categoryMapper.getById(parentId);
            // -- 判断查询结果是否为null
            if (parentCategory == null) {
                // -- 是：抛出ServiceException
                throw new MintmallServiceException(ResponseCode.NOT_FOUND,
                        "添加类别失败，父级类别不存在！");
            }
            // -- 否：当前depth >>> 父级depth + 1
            depth = parentCategory.getDepth() + 1;
        }

        // 创建Category对象
        Category category = new Category();
        // 调用BeanUtils.copyProperties()将参数对象中的属性值复制到Category对象中
        BeanUtils.copyProperties(categoryAddNewDTO, category);
        // 补全Category对象中的属性值：depth >>> 前序运算结果
        category.setDepth(depth);
        // 补全Category对象中的属性值：enable >>> 1（默认即启用）
        category.setEnable(1);
        // 补全Category对象中的属性值：isParent >>> 0
        category.setIsParent(0);
        // 补全Category对象中的属性值：gmtCreate, gmtModified >>> LocalDateTime.now()
        LocalDateTime now = LocalDateTime.now();
        category.setGmtCreate(now);
        category.setGmtModified(now);
        // 调用categoryMapper.insert(Category)插入类别数据，获取返回的受影响的行数
        int rows = categoryMapper.insert(category);
        // 判断返回的受影响的行数是否不为1
        if (rows != 1) {
            // 是：抛出ServiceException
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST,"添加类别失败,请稍后再试");
        }

    }

    @Override
    public List<Category> selectAll(Integer page,Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Category> categories = categoryMapper.selectAll();
        return categories;
    }

    @Override
    public int deleteById(Long id) {
        List<Category> categories = categoryMapper.listByParentId(id);
        if (!categories.isEmpty()){
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST,"该类别存在子类别,无法删除");
        }
        int rows = categoryMapper.deleteByIdInt(id);
        if (rows==0){
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST,"该类别不存在,请稍后再试");
        }
        return rows;
    }

    /**
     * 修改类别基本信息
     * @param category
     */
    @Override
    public void updateCategoryById(Category category) {
        CategorySimpleVO byName = categoryMapper.getByName(category.getName());
        if (byName!=null){
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST,"该类别名称已存在");
        }
        categoryMapper.updateCategoryById(category);
    }
}
